package com.kclmedu.sst.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/****************
 * 自定义登录成功的处理逻辑，比如处理异步登录请求
 */
public class SimpleAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private ObjectMapper objectMapper = new ObjectMapper();

    /**************
     * 编写登录成功的处理逻辑， 我们这里使用JSON来返回登录成功的提示信息
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //模拟一个Map
        Map<String, Boolean> result = new HashMap<>();
        //填充数据
        result.put("success",Boolean.TRUE);
        //转换成 json 字符串
        String json = objectMapper.writeValueAsString(result);
        System.out.println("--生成的JSON字符串是："+json);
        //把json写到客户端
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().println(json);
    }
}
